package ws

import (
	"flag"
	"github.com/gorilla/websocket"
	"sync"
	"time"
)

var flagMap sync.Map
var lock sync.Mutex

type WebsocketClientJs struct {
	conn          *websocket.Conn
	eventMap      map[string]interface{}
	ReadDeadline  time.Duration
	WriteDeadLine time.Duration
}

func getFlag(flagString string) *string {
	lock.Lock()
	if value, ok := flagMap.Load(flagString); ok {
		lock.Unlock()
		return value.(*string)
	}
	value := flag.String("addr", flagString, "http service address")
	flagMap.Store(flagString, value)
	lock.Unlock()
	return value
}
func (client *WebsocketClientJs) OnConnect(fun func(conn *websocket.Conn)) {
	if client.eventMap == nil {
		client.eventMap = map[string]interface{}{}
	}
	client.eventMap["onConnect"] = fun
}

func (client *WebsocketClientJs) OnError(fun func(err error)) {
	if client.eventMap == nil {
		client.eventMap = map[string]interface{}{}
	}
	client.eventMap["onError"] = fun
}

func (client *WebsocketClientJs) Connect(wsUrl string) {
	c, _, err := websocket.DefaultDialer.Dial(wsUrl, nil)
	client.conn = c
	if err != nil {
		if client.eventMap != nil && client.eventMap["onError"] != nil {
			fun := client.eventMap["onError"].(func(err2 error))
			fun(err)
		}
		return
	} else {
		if client.eventMap != nil && client.eventMap["onConnect"] != nil {
			fun := client.eventMap["onConnect"].(func(conn *websocket.Conn))
			fun(c)
		}
	}

	done := make(chan struct{})

	go func() {
		defer close(done)
		for {
			if client.ReadDeadline != 0 {
				c.SetReadDeadline(time.Now().Add(client.ReadDeadline))
			}
			_, message, err := c.ReadMessage()
			if err != nil {
				if client.eventMap != nil && client.eventMap["onDisconnect"] != nil {
					fun := client.eventMap["onDisconnect"].(func())
					fun()
				}
				return
			}
			//log.Printf("recv: %s", message)
			if client.eventMap != nil && client.eventMap["onMessage"] != nil {
				fun := client.eventMap["onMessage"].(func(string2 string))
				fun(string(message))
			}

		}
	}()
}
func (client *WebsocketClientJs) OnDisconnect(fun func()) {
	client.eventMap["onDisconnect"] = fun
}
func (client *WebsocketClientJs) OnMessage(fun func(msg string)) {
	if client.eventMap == nil {
		client.eventMap = map[string]interface{}{}
	}
	client.eventMap["onMessage"] = fun
}
func (client *WebsocketClientJs) Send(msg string) {
	if client.conn != nil {
		client.conn.WriteMessage(websocket.BinaryMessage, []byte(msg))
	}

}
func (client *WebsocketClientJs) Close() {
	if client.conn != nil {
		client.conn.Close()
	}
}
